//package com.jeffdouglas;
 package SendBoth;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
 
import com.sforce.ws.*;
import com.sforce.soap.partner.*;
import com.sforce.soap.partner.sobject.SObject;
 
public class SendChatterServlet extends HttpServlet {
 
  private static final Logger log = Logger.getLogger(SendTweetServlet.class);
 
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
  throws IOException {
 
    PartnerConnection connection = null;
    // get the user's last tweet
    String tweet = getLastTweet(req,resp);
 
    if (tweet != null) {
 
      try {
        if (connection == null) {
          ConnectorConfig config = new ConnectorConfig();
          config.setUsername(Credentials.SFDC_USERNAME);
          config.setPassword(Credentials.SFDC_PASSWORD);
          connection = Connector.newConnection(config);
        }
 
        // create the sobject to hold the post
        SObject post = new SObject();
        post.setType("FeedPost");
        post.setField("ParentId", Credentials.SFDC_USERID);
        post.setField("Body", tweet);
        // submit the update to Salesforce.com
        connection.create(new SObject[]{post});
 
      } catch (ConnectionException ce) {
        log.error(ce.toString());
      }
 
      resp.getWriter().println("Tweet sent to Chatter: "+tweet);
    } else {
      resp.getWriter().println("Could not fetch the lastes update from Twitter. Nothing sent to Chatter.");
    }
 
  }
 
  private String getLastTweet(HttpServletRequest req, HttpServletResponse resp) {
 
    String tweet = null;
    HttpSession session = req.getSession();
    Twitter twitter = new TwitterFactory().getInstance();
 
    twitter.setOAuthConsumer(Credentials.TWITTER_CONSUMERKEY,
        Credentials.TWITTER_CONSUMERSECRET);
 
    // if the access token is present in the session
    if (session.getAttribute("accessToken") == null){
        // get the request token from the session
        String token = (String) session.getAttribute("token");
        String tokenSecret = (String)session.getAttribute("tokenSecret");
 
        // get the access token from twitter
        AccessToken accessToken = null;
        try {
          accessToken = twitter.getOAuthAccessToken(token, tokenSecret);
        } catch (TwitterException e) {
          log.error(e.toString());
        }
        twitter.setOAuthAccessToken(accessToken);
 
        // save the access token, that are different from request token
        session.setAttribute("accessToken", accessToken.getToken());
        session.setAttribute("accessTokenSecret", accessToken.getTokenSecret());
 
    } else {
        // use the access token from the session
        twitter.setOAuthAccessToken((String)session.getAttribute("accessToken"),
            (String)session.getAttribute("accessTokenSecret"));
    }
 
    List<status> statuses = null;
    try {
      // get the user's timeline
      statuses = twitter.getUserTimeline();
      // set their last tweet to return
      tweet = statuses.get(0).getText();
    } catch (TwitterException e) {
      log.error(e.toString());
    }
 
    return tweet;
 
  }
 
}